package com.example.lesson

import android.util.Log
import com.example.core.base.BasePresenter
import com.example.core.http.EntityCallback
import com.example.core.http.HttpClient
import com.example.core.utils.ToastUtil
import com.example.lesson.entity.Lesson
import com.example.lesson.entity.State
import com.google.gson.reflect.TypeToken

class LessonPresenter(val activity: LessonActivity) : BasePresenter() {

    var lessons: List<Lesson> = arrayListOf()

    val lessonType = object : TypeToken<List<Lesson>>() {}.type

    fun fetchData() {
        HttpClient.INSTANCE.get(LESSON_PATH,lessonType,object :EntityCallback<List<Lesson>>{
            override fun onSuccess(entity: List<Lesson>) {
                Log.d(TAG, "onSuccess: ${Thread.currentThread().id}")
                lessons = entity
                activity.runOnUiThread{
                    activity.showLesson(entity)
                }

            }

            override fun onFailure(msg: String) {
                Log.d(TAG, "onFailure: ${Thread.currentThread().id}")
                activity.runOnUiThread{
                    ToastUtil.showToast(msg)
                    activity.closeRefresh()
                }
            }

        })
    }

    fun showPlayback() {
        val result = arrayListOf<Lesson>()
        lessons.forEach{
            if (it.state == State.PLAYBACK) {
                result.add(it)
            }
        }
        activity.showLesson(result)
    }

    companion object {
        private val LESSON_PATH = "lessons"
    }
}